package cn.darkhorse.workorder.service.impl;

import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;

import cn.darkhorse.workorder.domain.*;
import cn.darkhorse.workorder.mapper.QmsWorkorderRecordMapper;
import cn.darkhorse.workorder.service.*;
import cn.darkhorse.workorder.vo.QmsWorkorderVO;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.text.pdf.draw.LineSeparator;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.BarcodeUtils;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.PdfUtils;
import com.ruoyi.framework.config.ServerConfig;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import cn.darkhorse.workorder.mapper.QmsWorkorderMapper;

/**
 * 流转单Service业务层处理
 *
 * @author ytq
 * @date 2024-07-19
 */
@Service
public class QmsWorkorderServiceImpl extends ServiceImpl<QmsWorkorderMapper, QmsWorkorder> implements IQmsWorkorderService
{
    @Autowired
    private QmsWorkorderMapper qmsWorkorderMapper;
    @Autowired
    private QmsWorkorderRecordMapper qmsWorkorderRecordMapper;
    @Autowired
    private IQmsWorkorderLogService qmsWorkorderLogService;
    @Autowired
    private IQmsWorkorderBalanceInfoService balanceInfoService;
    @Autowired
    private ServerConfig serverConfig;

    /**
     * 查询流转单
     *
     * @param id 流转单主键
     * @return 流转单
     */
    @Override
    public QmsWorkorder selectQmsWorkorderById(Long id) {
        return qmsWorkorderMapper.selectQmsWorkorderById(id);
    }

    /**
     * 查询流转单列表
     *
     * @param qmsWorkorder 流转单
     * @return 流转单
     */
    @Override
    public List<QmsWorkorder> selectQmsWorkorderList(QmsWorkorder qmsWorkorder) {

        QueryWrapper<QmsWorkorder> queryWrapper = new QueryWrapper<>();
        if (qmsWorkorder.getOrderNumber()!=null){
            queryWrapper.like("order_number",qmsWorkorder.getOrderNumber());
        }
        if (qmsWorkorder.getProcessors()!=null){
            queryWrapper.like("processors",qmsWorkorder.getProcessors());
        }
        if (qmsWorkorder.getProcessorsCode()!=null){
            queryWrapper.like("processors_code",qmsWorkorder.getProcessorsCode());
        }
        if (qmsWorkorder.getStartEndTime()!=null){
            queryWrapper.between("start_time",qmsWorkorder.getStartBeginTime(),processTime(qmsWorkorder.getStartEndTime()));
        }
        if (qmsWorkorder.getEndEndTime()!=null){
            queryWrapper.between("end_time",qmsWorkorder.getEndBeginTime(),processTime(qmsWorkorder.getEndEndTime()));
        }
        if (qmsWorkorder.getStatus()!=null){
            queryWrapper.eq("status",qmsWorkorder.getStatus());
        }
        if (qmsWorkorder.getBatchNumber()!=null){
            queryWrapper.like("batch_number",qmsWorkorder.getBatchNumber());
        }
        if (qmsWorkorder.getRegiment()!=null){
            queryWrapper.like("regiment",qmsWorkorder.getRegiment());
        }
        queryWrapper.orderByDesc("id");
        return list(queryWrapper);
    }
    public Date processTime(Date time) {
        if (time != null) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(time); // 设置当前时间

            // 设置时间为当天的 23:59:59
            calendar.set(Calendar.HOUR_OF_DAY, 23);
            calendar.set(Calendar.MINUTE, 59);
            calendar.set(Calendar.SECOND, 59);
            calendar.set(Calendar.MILLISECOND, 0); // 清零毫秒

            return calendar.getTime();
        }
        return DateUtils.getNowDate();
    }

    /**
     * 新增流转单
     *
     * @param qmsWorkorder 流转单
     * @return 结果
     */
    @Override
    public boolean saveQmsWorkorder(QmsWorkorder qmsWorkorder) {
        if (qmsWorkorder.getId() == null){
            // 构造文件URL

            QmsWorkorderLog workorderLog = new QmsWorkorderLog();
            Long count = lambdaQuery().eq(QmsWorkorder::getOrderNumber, qmsWorkorder.getOrderNumber()).count();
            if (count>0){
                throw new RuntimeException("流转单编号已存在");
            }
            count = lambdaQuery().eq(QmsWorkorder::getBatchNumber, qmsWorkorder.getBatchNumber()).count();
            if (count>0){
                throw new RuntimeException("批号已存在");
            }

            save(qmsWorkorder);
//            JSONObject object = new JSONObject();
//            object.put("id", qmsWorkorder.getId());
//            object.put("systemName", "cotton");
            String s = BarcodeUtils.generateAndUploadFile(qmsWorkorder.getId().toString(),qmsWorkorder.getOrderNumber());
            qmsWorkorder.setBarCode(s);
            updateById(qmsWorkorder);

            QmsWorkorderBalanceInfo balanceInfo = new QmsWorkorderBalanceInfo();
            balanceInfo.setOrderNumber(qmsWorkorder.getOrderNumber());
            balanceInfo.setOrderId(qmsWorkorder.getId());
            balanceInfo.setType(1);
            balanceInfoService.save(balanceInfo);
            balanceInfo.setType(2);
            balanceInfo.setId(null);
            balanceInfoService.save(balanceInfo);
            balanceInfo.setType(3);
            balanceInfo.setId(null);
            balanceInfoService.save(balanceInfo);


            workorderLog.setOrderNumber(qmsWorkorder.getOrderNumber());
            workorderLog.setWorkorderId(qmsWorkorder.getId());

            qmsWorkorderLogService.save(workorderLog);

            return true;
        }else{
            QmsWorkorder workorder = getById(qmsWorkorder.getId());

            Long count = lambdaQuery().eq(QmsWorkorder::getOrderNumber, qmsWorkorder.getOrderNumber()).ne(QmsWorkorder::getId,qmsWorkorder.getId()).count();
            if (count>0){
                throw new RuntimeException("流转单编号已存在");
            }
            count = lambdaQuery().eq(QmsWorkorder::getBatchNumber, qmsWorkorder.getBatchNumber()).ne(QmsWorkorder::getId,qmsWorkorder.getId()).count();
            if (count>0){
                throw new RuntimeException("批号已存在");
            }
            Integer status = workorder.getStatus();
            Integer nowStatus = qmsWorkorder.getStatus();
            if (!status.equals(nowStatus)){
                if (nowStatus>status){
//                    检查是否已经填过
                    QmsWorkorderLog workorderLog = qmsWorkorderLogService.lambdaQuery().eq(QmsWorkorderLog::getOrderNumber, qmsWorkorder.getOrderNumber()).one();
                    if (workorderLog!=null){
                        boolean b = workorderLog.hasNullBeforeStatus(nowStatus);
                        if (b){
                            throw new RuntimeException("无法设置为此状态，因为有前置步骤未完成");
                        }else {
                            UpdateWrapper<QmsWorkorderLog> updateWrapper = new UpdateWrapper<>();
                            updateWrapper.set(QmsWorkorderLog.getColumnByStatus(nowStatus), null);
                            updateWrapper.eq("order_number",qmsWorkorder.getOrderNumber());
                            qmsWorkorderLogService.update(updateWrapper);
                        }
                    }

                }else {
                    UpdateWrapper<QmsWorkorderLog> updateWrapper = new UpdateWrapper<>();
                    updateWrapper.set(QmsWorkorderLog.getColumnByStatus(nowStatus), null);
                    updateWrapper.eq("order_number",qmsWorkorder.getOrderNumber());
                    qmsWorkorderLogService.update(updateWrapper);
                }
            }
            return updateById(qmsWorkorder);
        }
    }

    /**
     * 批量删除流转单
     *
     * @param ids 需要删除的流转单主键
     * @return 结果
     */
    @Override
    public int deleteQmsWorkorderByIds(Long[] ids) {
        return qmsWorkorderMapper.deleteQmsWorkorderByIds(ids);
    }

    /**
     * 删除流转单信息
     *
     * @param id 流转单主键
     * @return 结果
     */
    @Override
    public boolean deleteQmsWorkorderById(Long id) {
        QmsWorkorder workorder = getById(id);
        qmsWorkorderLogService.lambdaUpdate().eq(QmsWorkorderLog::getOrderNumber,workorder.getOrderNumber()).remove();
        return removeById(id);
    }

    @Override
    public String getOrderNumber() {
        // 获取当前日期并格式化为字符串
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String dateStr = sdf.format(new Date());

        // 生成一个4位的随机数
        Random random = new Random();
        int randomNum = random.nextInt(9999);
        // 如果随机数小于1000，补零到4位
        String randomStr = String.format("%04d", randomNum);

        // 拼接日期和随机数
        String number = dateStr + randomStr;
        if (this.lambdaQuery().eq(QmsWorkorder::getOrderNumber, number).count()>0){
            return getOrderNumber();
        }
        return number;
    }

    @Override
    public boolean doUpload(QmsWorkorder workorder) {
        workorder = getById(workorder.getId());
        Long count = qmsWorkorderLogService.lambdaQuery().eq(QmsWorkorderLog::getOrderNumber, workorder.getOrderNumber())
                .isNotNull(QmsWorkorderLog::getUpload).count();
        if (count>0){
            throw new RuntimeException("请勿重复上传");
        }

        Date nowDate = DateUtils.getNowDate();
        qmsWorkorderLogService.lambdaUpdate().set(QmsWorkorderLog::getUpload,nowDate)
                .eq(QmsWorkorderLog::getOrderNumber,workorder.getOrderNumber())
                .update();
        workorder.setStatus(6);
        workorder.setUploadTime(nowDate);
        if (workorder.getEndTime()==null){
            workorder.setEndTime(nowDate);
        }
        if (workorder.getStartTime()==null){
            workorder.setStartTime(workorder.getCreateTime());
        }

        return updateById(workorder);
    }

    @Override
    public QmsWorkorder view(Long id) {


        QmsWorkorder qmsWorkorder = qmsWorkorderRecordMapper.selectQmsWorkorderById(id);

        if (qmsWorkorder == null){
            throw new RuntimeException("未找到该数据");
        }
        QmsWorkorderSampleBalance balance = qmsWorkorder.getWorkorderSampleBalance();
        if (balance!=null){
            balance.setDeliveryTestRecords(JSONArray.parseArray(balance.getDeliveryTestRecord(), QmsWorkorderSampleBalanceRecord.class));
            balance.setBeforeTestRecords(JSONArray.parseArray(balance.getBeforeTestRecord(), QmsWorkorderSampleBalanceRecord.class));
            balance.setAfterTestRecords(JSONArray.parseArray(balance.getAfterTestRecord(), QmsWorkorderSampleBalanceRecord.class));
            qmsWorkorder.setWorkorderSampleBalance(balance);
        }
        QmsWorkorderLog log = qmsWorkorderLogService.getByOrderNumber(qmsWorkorder.getOrderNumber());
        qmsWorkorder.setStatusOverTimes(log);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        if (log!=null){
            JSONObject timeLine = getTimeLine(log, format);
            qmsWorkorder.setTimeLine(timeLine);
        }

        return qmsWorkorder;
    }

    @Override
    public QmsWorkorderVO viewMain(Long id) {
        QmsWorkorderVO workorderVO = new QmsWorkorderVO();
        QmsWorkorder workorder = getById(id);
        if (workorder!=null){
            BeanUtils.copyProperties(workorder,workorderVO);
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            if (workorder.getStartTime()!=null){
                workorderVO.setStartTime(format.format(workorder.getStartTime()));
            }
            if(workorder.getEndTime()!=null){
                workorderVO.setEndTime(format.format(workorder.getEndTime()));
            }

            QmsWorkorderLog log = qmsWorkorderLogService.lambdaQuery().eq(QmsWorkorderLog::getOrderNumber, workorder.getOrderNumber()).one();
            workorder.setStatusOverTimes(log);

            if (log!=null){
                workorderVO.setTimeLine(getTimeLine(log, format));
            }

        }
        return workorderVO;
    }

    @Override
    public File findWorkOrderDetail(QmsWorkorder workorder,String img) {
        try {

            //导出方法
            String path="";
            String fileName="workOrder"+ DateUtils.dateTime()+ UUID.randomUUID()+".pdf";
            String filePath= RuoYiConfig.getDownloadPath()+"/orderPdf/"+fileName;
            filePath= systemDelimiter(filePath);
            path= "/orderPdf/"+fileName;
            // 2.建立一个书写器(Writer)与document对象关联
            File file = new File(filePath);
            if (!file.getParentFile().exists())
            {
                file.getParentFile().mkdirs();
            }
            file.createNewFile();

            // 1.新建document对象 建立一个Document对象
            Document document = new Document(PageSize.A4);
            PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));

            // 3.打开文档
            document.open();
            document.addTitle(workorder.getOrderNumber());// 标题
            document.addAuthor("chuz");// 作者
            document.addSubject("Subject@iText pdf sample");// 主题
            document.addKeywords("Keywords@iTextpdf");// 关键字
            document.addCreator("chuz develop");// 创建者
            // 4.向文档中添加内容
            generatePDF(document,workorder,writer,img);
            // 5.关闭文档
            document.close();
            writer.close();
            return file;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

//     生成PDF文件
    public void generatePDF(Document document,QmsWorkorder workorder,PdfWriter writer,String imgUrl) {

        Image image= PdfUtils.getImage(imgUrl, writer);;

        QmsWorkorderLog workorderLog = qmsWorkorderLogService.lambdaQuery().eq(QmsWorkorderLog::getOrderNumber, workorder.getOrderNumber()).one();
        //添加总标题,
        try {
            PdfUtils.addTitle(document,"内部流转卡",0);
            PdfUtils.addFirstTitle(document,workorder.getProcessors(),0);
            // 基本信息-一级标题
            // 一条横线
            Paragraph p1 =new Paragraph();
            LineSeparator lineSeparator = new LineSeparator();
            lineSeparator.setLineColor(new BaseColor(8,106,199));
            p1.add(new Chunk(lineSeparator));
            document.add(p1);

            if (image!=null){
                image.scaleAbsolute(160, 35);
                image.setAbsolutePosition(400,750);
                document.add(image);
            }

            PdfPTable table = PdfUtils.createTable(3,480);
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            PdfUtils.addNoBorderCell(table,"工单编码",PdfUtils.paragraphBoldFont);
            PdfUtils.addNoBorderCell(table,"批号",PdfUtils.paragraphBoldFont);
            PdfUtils.addNoBorderCell(table,"开始日期",PdfUtils.paragraphBoldFont);
            PdfUtils.addNoBorderCell(table,workorder.getOrderNumber(),PdfUtils.paragraphFont);
            PdfUtils.addNoBorderCell(table,workorder.getBatchNumber(),PdfUtils.paragraphFont);
            PdfUtils.addNoBorderCell(table,format.format(workorder.getStartTime()),PdfUtils.paragraphFont);
            document.add(table);
            PdfUtils.addLine(document,new BaseColor(215,217,217),0.5f);
            PdfPTable table2 = PdfUtils.createTable(1,480);
            PdfUtils.addNoBorderCell(table2,"检验类型",PdfUtils.paragraphBoldFont);
            PdfUtils.addNoBorderCell(table2,"公证检验",PdfUtils.paragraphFont);
            document.add(table2);
            PdfUtils.addLine(document,new BaseColor(215,217,217),0.5f);

            document.add(new Paragraph("\n\n"));

            document.add(p1);


            PdfPTable tableTitle = PdfUtils.createTable(4,480);
            PdfUtils.addNoBorderCell(tableTitle,"序号",PdfUtils.tableTitleFont);
            PdfUtils.addNoBorderCell(tableTitle,"处理部门",PdfUtils.tableTitleFont);
            PdfUtils.addNoBorderCell(tableTitle,"完成情况",PdfUtils.tableTitleFont);
            PdfUtils.addNoBorderCell(tableTitle,"处理人",PdfUtils.tableTitleFont);

            document.add(tableTitle);
            PdfUtils.addLine(document,new BaseColor(215,217,217),0.5f);

            PdfPTable tableCell = PdfUtils.createTable(4,480);

            PdfUtils.addNoBorderCell(tableCell,"1",PdfUtils.tableCellFont);
            PdfUtils.addNoBorderCell(tableCell,"取送样品交接",PdfUtils.tableCellFont);
            PdfUtils.addNoBorderCell(tableCell,"\u25A1",PdfUtils.tableCellBoldFont);
            PdfUtils.addNoBorderCell(tableCell,"",PdfUtils.tableCellFont);


            PdfUtils.addNoBorderCell(tableCell,"2",PdfUtils.tableCellFont);
            PdfUtils.addNoBorderCell(tableCell,"感官检验",PdfUtils.tableCellFont);
            PdfUtils.addNoBorderCell(tableCell,"\u25A1",PdfUtils.tableCellBoldFont);
            PdfUtils.addNoBorderCell(tableCell,"",PdfUtils.tableCellFont);


            PdfUtils.addNoBorderCell(tableCell,"3",PdfUtils.tableCellFont);
            PdfUtils.addNoBorderCell(tableCell,"样品平衡",PdfUtils.tableCellFont);
            PdfUtils.addNoBorderCell(tableCell,"\u25A1",PdfUtils.tableCellBoldFont);
            PdfUtils.addNoBorderCell(tableCell,"",PdfUtils.tableCellFont);


            PdfUtils.addNoBorderCell(tableCell,"4",PdfUtils.tableCellFont);
            PdfUtils.addNoBorderCell(tableCell,"HVI检验",PdfUtils.tableCellFont);
            PdfUtils.addNoBorderCell(tableCell,"\u25A1",PdfUtils.tableCellBoldFont);
            PdfUtils.addNoBorderCell(tableCell,"",PdfUtils.tableCellFont);


            document.add(tableCell);

            document.add(new Paragraph("\n\n\n\n\n\n"));
            PdfUtils.addLine(document,new BaseColor(215,217,217),0.5f);
            document.add(new Paragraph("\n\n"));




            Paragraph paragraph = new Paragraph("棉花质量公证检验内部流转单系统",PdfUtils.footFont);
            paragraph.setAlignment(0); //设置文字居中 0靠左   1，居中     2，靠右
            paragraph.setIndentationLeft(0); //设置左缩进
            paragraph.setIndentationRight(12); //设置右缩进
            paragraph.setFirstLineIndent(0); //设置首行缩进
            paragraph.setLeading(10f); //行间距
            document.add(paragraph);

            Paragraph paragraph2 = new Paragraph();
            paragraph2.setAlignment(0); //设置文字居中 0靠左   1，居中     2，靠右
            paragraph2.setIndentationLeft(0); //设置左缩进
            paragraph2.setIndentationRight(12); //设置右缩进
            paragraph2.setFirstLineIndent(0); //设置首行缩进
            paragraph2.setLeading(10f); //行间距
            paragraph2.add(new Chunk("新疆宜棉智能科技有限公司 ",PdfUtils.footFont2));
            Font unicodeFontStyle = FontFactory.getFont(FontFactory.SYMBOL, 7, Font.BOLD, new BaseColor(86, 110, 112));
            paragraph2.add(new Chunk("\u00E3 2024",unicodeFontStyle));
            document.add(paragraph2);
        } catch (DocumentException e) {
            throw new RuntimeException(e);
        }


        // 其它约定
        //PdfUtils.createTextParagraph(document,"黑马MOM系统",0);
    }

    private JSONObject getTimeLine(QmsWorkorderLog log, SimpleDateFormat format) {
        JSONObject timeLine = new JSONObject();
        if (log.getDelivery()!=null){
            timeLine.put("delivery",format.format(log.getDelivery()));
        }else {
            timeLine.put("delivery", null);
        }
        if (log.getSense()!=null){
            timeLine.put("sense",format.format(log.getSense()));
        }else {
            timeLine.put("sense", null);
        }
        if (log.getBalance()!=null){
            timeLine.put("balance",format.format(log.getBalance()));
        }else {
            timeLine.put("balance", null);
        }
        if (log.getHvi()!=null){
            timeLine.put("hvi",format.format(log.getHvi()));
        }else {
            timeLine.put("hvi", null);
        }
        if (log.getAudit()!=null){
            timeLine.put("audit",format.format(log.getAudit()));
        }else {
            timeLine.put("audit", null);
        }
        if (log.getUpload()!=null){
            timeLine.put("upload",format.format(log.getUpload()));
        }else {
            timeLine.put("upload", null);
        }
        return timeLine;
    }

    private void nextStatus(String number){
        QmsWorkorder workorder = this.lambdaQuery().eq(QmsWorkorder::getOrderNumber, number).one();
        QmsWorkorderLog log = qmsWorkorderLogService.lambdaQuery().eq(QmsWorkorderLog::getOrderNumber, number).one();

        if (log.getAudit()!=null){
            workorder.setStatus(5);
        }else if (log.getHvi()!=null){
            workorder.setStatus(4);
        }else if (log.getBalance()!=null){
            workorder.setStatus(3);
        }else if (log.getSense()!=null){
            workorder.setStatus(2);
        }else if (log.getDelivery()!=null){
            workorder.setStatus(1);
        }

        this.updateById(workorder);
//        qmsWorkorderSampleDeliveryService.lambdaQuery().eq(get);
    }
    public static String systemDelimiter(String path){
        String sysType = System.getProperty("os.name").toLowerCase();
        if(sysType.contains("win")){
            return  path;
        }else if(sysType.contains("linux")){
            return path.replace("\\","/");
        }else {
            throw new ServiceException("未知系统！");
        }
    }
}
